<?php
declare(strict_types=1);
/**
 * Grace is committed to providing solutions for quickly building web applications
 * Please view the LICENSE file that was distributed with this source code,
 * For the full copyright and license information.
 * Thank you very much for using Grace.
 *
 * @Author kiki
 */

namespace App\Common\Service;

use App\Common\Mapper\CommonUserMapper;
use App\Common\Service\Tool\ConstantsService;
use App\Common\Service\Tool\JwtService;
use Hyperf\Di\Annotation\Inject;
use Mine\Abstracts\AbstractService;
use Mine\Exception\NormalStatusException;

/**
 * 平台用户服务类
 */
class CommonUserService extends AbstractService
{
    /**
     * @var CommonUserMapper
     */
    public $mapper;

    #[Inject]
    protected JwtService $jwtService;

    public function __construct(CommonUserMapper $mapper)
    {
        $this->mapper = $mapper;
    }

    /**
     * 新增数据
     * @param array $data
     * @return int
     */
    public function save(array $data): int
    {
        return $this->mapper->save($data);
    }

    /**
     * api登录
     * @param array $data
     * @return int
     */
    public function login(array $data)
    {
        $model = $this->mapper->first(['account' => $data['account']]);
        if (!$model) {
            throw new NormalStatusException('账号不存在');
        }
        $model = $model->toArray();
        if (md5($data['pwd']) != $model['pwd_hash']) {
            throw new NormalStatusException('密码错误');
        }

        $token = $this->jwtService->token($model['id'])['token'] ?? "";
        $token = $token . '####' . $model['id'];

        // 改用redis缓存
        redis()->set(ConstantsService::API_TOKEN . $model['id'], $token, config('jwt.ttl'));

        return ['token' => $token];
    }
}